#include <stdio.h>
#include <string.h>
#include <mysql/mysql.h>

#define HOST "127.0.0.1"
#define USER "root"
#define PORT 3306
#define PASSWD "123456"
#define DBNAME "gobang"

int main()
{
    //1.初始化mysql句柄
    //这里为空，表示由系统在堆上面申请空间创建MYSQL对象
    MYSQL* mysql = mysql_init(NULL);
    if(mysql == NULL)
    {
        printf("mysql init fail\n");
        return -1;
    }

    //2.连接服务器
    if(mysql_real_connect(mysql, HOST, USER, PASSWD, DBNAME, PORT, NULL, 0) == NULL)
    {
        printf("mysql connect fail, error: %s\n", mysql_error(mysql));
        mysql_close(mysql);
        return -1;
    }

    //3.设置客户端字符集
    if(mysql_set_character_set(mysql, "utf8mb4") != 0)
    {
        printf("set client character fail, error: %s\n", mysql_error(mysql));
        mysql_close(mysql);
        return -1;
    }

    //4.选择要操作的数据库
    //这里因为前面连接服务器时已经设置了数据库，这里可以不写
    //mysql_select_db(mysql, DB);

    //5.执行sql语句
    //const char* sql = "insert into stu values(null, '好友', 16, 55.6, 70, 80);";
    //const char* sql = "update stu set ch=ch+20 where id=2";
    //const char* sql = "delete from stu where id = 2";
    const char* sql = "select * from stu";

    if(mysql_query(mysql, sql) != 0)
    {
        printf("%s\n", sql);
        printf("mysql query fail, error: %s\n", mysql_error(mysql));
        mysql_close(mysql);
        return -1;
    }

    //6.如果sql语句是查询语句，则需要保存结果到本地
    MYSQL_RES* res = mysql_store_result(mysql);
    if(res == NULL)
    {
        mysql_close(mysql);
        return 0;
    }

    //7.获取结果集中的结果条数
    //结果集行数
    int row = mysql_num_rows(res);
    //结果集列数
    int col = mysql_num_fields(res);

    //8.遍历保存到本地的结果集
    for(int i = 0;i < row;i++)
    {
        MYSQL_ROW row_data = mysql_fetch_row(res);
        for(int j = 0;j < col;j++)
        {
            printf("%s\t", row_data[j]);
        }
        printf("\n");
    }

    //9.释放结果集
    mysql_free_result(res);

    //10.关闭连接，释放句柄
    mysql_close(mysql);
    return 0;
}